<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">

      <!-- 主菜单 -->
      <el-menu
        v-if="!showProfileSubMenu"
        active-text-color="#ffd04b"
        background-color="#232323"
        :default-active="activeMenu"
        text-color="#fff"
        router
      >
        <!-- 主菜单标题 -->
        <el-menu-item index="/employee">
          <el-icon><Menu /></el-icon>
          <span>主菜单</span>
        </el-menu-item>

        <!-- 工作内容录入 -->
        <el-menu-item index="/employee/work-input">
          <el-icon><Management /></el-icon>
          <span>工作内容录入</span>
        </el-menu-item>

        <!-- 工作内容查看 -->
        <el-menu-item index="/employee/work-list">
          <el-icon><Promotion /></el-icon>
          <span>工作内容查看</span>
        </el-menu-item>

        <!-- 目标管理 -->
        <el-menu-item index="/employee/target">
          <el-icon><Aim /></el-icon>
          <span>目标管理</span>
        </el-menu-item>

        <!-- 绩效统计 -->
        <el-menu-item index="/employee/performance">
          <el-icon><DataLine /></el-icon>
          <span>绩效统计</span>
        </el-menu-item>

        <!-- 通知与提醒 -->
        <el-menu-item index="/employee/notification">
          <el-icon><Bell /></el-icon>
          <span>通知与提醒</span>
        </el-menu-item>

        <!-- 个人中心入口 -->
        <el-menu-item @click="showProfileSubMenu = true">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>

      <!-- 个人中心子菜单 -->
      <el-menu
        v-else
        active-text-color="#ffd04b"
        background-color="#232323"
        text-color="#fff"
        :default-active="activeMenu"
        router
      >
        <!-- 返回按钮 -->
        <el-menu-item @click="showProfileSubMenu = false">
          <el-icon><ArrowLeft /></el-icon>
          <span>返回主菜单</span>
        </el-menu-item>

        <!-- 个人中心子菜单项 -->
        <el-menu-item index="/employee/profile">
          <el-icon><User /></el-icon>
          <span>基本资料</span>
        </el-menu-item>
        <el-menu-item index="/employee/avatar">
          <el-icon><Crop /></el-icon>
          <span>更换头像</span>
        </el-menu-item>
        <el-menu-item index="/employee/repassword">
          <el-icon><EditPen /></el-icon>
          <span>重置密码</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区域 -->
    <el-container>
      <!-- 头部 -->
      <el-header>
        <div></div>
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <el-avatar :src="avatar" />
            <el-icon><CaretBottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="/employee/profile" :icon="User">基本资料</el-dropdown-item>
              <el-dropdown-item command="/employee/avatar" :icon="Crop">更换头像</el-dropdown-item>
              <el-dropdown-item command="/employee/repassword" :icon="EditPen"
                >重置密码</el-dropdown-item
              >
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <!-- 主内容区域 -->
      <el-main>
        <router-view @menu-change="handleMenuChange"></router-view>
      </el-main>

      <!-- 底部 -->
      <el-footer>Created by Goalance</el-footer>
    </el-container>

    <!-- 全局未读消息弹窗 -->
    <UnreadMessageModal ref="unreadModal" />
  </el-container>
</template>

<script setup>
import { ref, computed, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import {
  Menu,
  Management,
  Promotion,
  Aim,
  DataLine,
  Bell,
  User,
  Crop,
  EditPen,
  ArrowLeft,
  CaretBottom,
  SwitchButton,
} from '@element-plus/icons-vue'
import UnreadMessageModal from './employee/UnreadMessageModal.vue'
import { getUnreadNotifications } from '@/api/notification'

const route = useRoute()
const router = useRouter()
const useStore = useUserStore()
// 获取全局挂载的 $apiBaseUrl
const { proxy } = getCurrentInstance()
const unreadModal = ref(null)
const avatar = computed(() => {
  return useStore.user.avatar ? proxy.$apiBaseUrl + '/' + useStore.user.avatar : '' // 或者默认头像
})
const showProfileSubMenu = ref(false)
const activeMenu = computed(() => route.path)
const lastCheckTime = ref(null) // 存储最后一次检查时间
const CHECK_INTERVAL = 2 * 60 * 60 * 1000

// 计算相对时间（优化版）
const formatTimeAgo = (dateString) => {
  const now = new Date()
  const date = new Date(dateString)

  // 添加日期有效性检查
  if (isNaN(date.getTime())) {
    console.error('无效的日期格式:', dateString)
    return '未知时间'
  }

  const diffInSeconds = Math.floor((now - date) / 1000)

  const intervals = {
    年: 31536000,
    月: 2592000,
    周: 604800,
    天: 86400,
    小时: 3600,
    分钟: 60,
  }

  for (const [unit, seconds] of Object.entries(intervals)) {
    const interval = Math.floor(diffInSeconds / seconds)
    if (interval >= 1) {
      return `${interval}${unit}前`
    }
  }

  return '刚刚'
}

// 检查未读消息（优化版）
const checkUnreadMessages = async () => {
  try {
    const response = await getUnreadNotifications()

    if (!response?.data || response.data.code !== 200 || !Array.isArray(response.data.data)) {
      console.error('API数据验证失败', response)
      return
    }

    const notifications = response.data.data // 实际通知数组
    if (notifications.length > 0) {
      const oldestNotification = notifications.reduce((oldest, current) => {
        return new Date(oldest.createdAt) < new Date(current.createdAt) ? oldest : current
      })

      unreadModal.value?.show(notifications.length, formatTimeAgo(oldestNotification.createdAt))
    }
    lastCheckTime.value = new Date()
  } catch (error) {
    console.error('获取未读消息失败:', error)
  }
}

// 定时检查
const setupIntervalCheck = () => {
  checkUnreadMessages() // 立即执行一次
  setInterval(checkUnreadMessages, CHECK_INTERVAL)
}

// 焦点事件处理
const handleFocusCheck = () => {
  if (!document.hidden && lastCheckTime.value) {
    const now = new Date()
    const timeSinceLastCheck = now - lastCheckTime.value

    // 如果超过2小时未检查，或者从未检查过
    if (timeSinceLastCheck > CHECK_INTERVAL) {
      checkUnreadMessages()
    }
  }
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    router.push('/login')
  } else {
    router.push(command)
    // 如果跳转到个人中心相关页面，显示子菜单
    if (
      command.includes('/employee/profile') ||
      command.includes('/employee/avatar') ||
      command.includes('/employee/repassword')
    ) {
      showProfileSubMenu.value = true
    } else {
      showProfileSubMenu.value = false
    }
  }
}

// 处理子组件发来的菜单更新请求
const handleMenuChange = (path) => {
  router.push(path)
}

onMounted(() => {
  // 首次检查延迟1秒
  setTimeout(checkUnreadMessages, 1000)

  // 初始化
  onMounted(() => {
    setupIntervalCheck()
    window.addEventListener('focus', handleFocusCheck)
  })

  // 清理
  onBeforeUnmount(() => {
    window.removeEventListener('focus', handleFocusCheck)
  })
})
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100vh;
  .el-aside {
    background-color: #232323;
    position: relative;
    .el-menu {
      border-right: none;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      transition: all 0.3s ease;
    }
  }
  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .el-dropdown__box {
      display: flex;
      align-items: center;
      .el-icon {
        color: #999;
        margin-left: 10px;
      }
      &:active,
      &:focus {
        outline: none;
      }
    }
  }
  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }
}

/* 返回按钮样式 */
.el-menu-item:first-child {
  border-bottom: 1px solid #444;
  margin-bottom: 5px;
  color: #ffd04b;
}

/* 取消工作内容录入的激活状态 */
.el-menu-item.is-active[index='/employee/work-input'] {
  color: #fff !important;
  background-color: transparent !important;
}
.el-menu-item.is-active[index='/employee/work-input']:hover {
  background-color: rgba(255, 208, 75, 0.1) !important;
}
</style>
